﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Net;

namespace DotSpider.Controls
{
    public static class Settings
    {
        public static bool UpdateQueueList;

        public static bool UseProxy()
        {
            return "true" == GetVariable("enable", "Proxy.xml");
        }
        public static WebProxy GetProxy(bool auth)
        {
            string filename = "Proxy.xml";
            WebProxy proxy =
                new WebProxy("http://" + GetVariable("address", filename) + ":" + GetVariable("port", filename), true);
            if (auth)
            {
                proxy.Credentials =
                    new NetworkCredential(GetVariable("username", filename), 
                        GetVariable("password", filename));
            }
            return proxy;
        }

        public static float Progress;
        public static string GrepPageTitle(string content)
        {
            try
            {
                Regex rxTitle = new Regex(@"<title>([^<]+)</title>", RegexOptions.IgnoreCase);
                return rxTitle.Match(content).Groups[1].Captures[0].ToString();
            } 
            catch(Exception e)
            {
                return "";
            }
        }

        public static string FixURL(string site, string url)
        {
            if (url[0] == '\'') { url = url.Remove(0, 1); }
            if (url[url.Length-1] == '\'') { url = url.Remove(url.Length-1, 1); }
            string result = url;

            if (Regex.IsMatch(url,@"^http\:\/\/")
                || Regex.IsMatch(url, @"^https\:\/\/"))
            {
                return url;
            }

            if (url.IndexOf("mailto") == 0
                || url.IndexOf("javascript") == 0
                || url.IndexOf("#") == 0
                || url.Contains("@")) return ""; //HACK
            try
            {
                //Uri uri = new Uri(site);
                //bool uriDone = Uri.TryCreate(new Uri(site), new Uri(url), out uri);
                //if (uriDone) return uri.ToString();

                Uri homeUri = new Uri(site);
                if (url.IndexOf('/') == 0)
                {
                    return "http://" + homeUri.Host + url;
                }

                //try
                Uri nUrl = new Uri("http://" + homeUri.Host
                   + (homeUri.Segments[0] == "/" && homeUri.Segments.Length > 1 ? "" : "/")
                   + string.Join("", homeUri.Segments, 0, homeUri.Segments.Length - 1) + url);

                return "http://" + homeUri.Host
                   + (homeUri.Segments[0] == "/" && homeUri.Segments.Length > 1 ? "" : "/")
                   + string.Join("", homeUri.Segments, 0, homeUri.Segments.Length - 1) + url;
            } 
            catch (Exception e)
            {
                return "";
            }
        }

        public static class Logger
        {
            public static List<string> GetLog()
            {
                return _Log;
            }
            private static List<string> _Log = new List<string>();
            public static void AddLog(string data)
            {
                _Log.Add(string.Format("{0}:{1}:{2}.{3} > {4}",
                            DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second,
                            DateTime.Now.Millisecond,
                            data));
            }
            public static void Clear()
            {
                _Log = new List<string>();
            }
        }

        public static Dictionary<string, int> Words;

        public static string GetVariable(string varName, string filename)
                    {
                        try
                        {
                            XmlDocument xml = new XmlDocument();
                            xml.Load(filename);
                            return (xml.DocumentElement.GetElementsByTagName(varName)[0]).InnerText;
                        }
                        catch(Exception)
                        {
                            throw new Exception("Can't find database settings file");
                        }
                    }

        public static class Database
        {
            public static string DbConfigFile = "DbSettings.xml";
            

            private static string _Server;
            public static string Server
            {
                get
                {
                    if(string.IsNullOrEmpty(_Server))
                        _Server = GetVariable("server", DbConfigFile);
                    return _Server;
                }
            }

            private static string _Port;
            public static string Port
            {
                get
                {
                    if (string.IsNullOrEmpty(_Port))
                        _Port = GetVariable("port", DbConfigFile);
                    return _Port;
                }
            }

            private static string _Username;
            public static string Username
            {
                get
                {
                    if (string.IsNullOrEmpty(_Username))
                        _Username = GetVariable("username", DbConfigFile);
                    return _Username;
                }
            }

            private static string _Password;
            public static string Password
            {
                get
                {
                    if (string.IsNullOrEmpty(_Password))
                        _Password = GetVariable("password", DbConfigFile);
                    return _Password;
                }
            }

            private static string _Dbname;
            public static string Dbname
            {
                get
                {
                    if (string.IsNullOrEmpty(_Dbname))
                        _Dbname = GetVariable("dbname", DbConfigFile);
                    return _Dbname;
                }
            }
            private static string _Driver;
            public static string Driver
            {
                get
                {
                    if (string.IsNullOrEmpty(_Driver))
                        _Driver = GetVariable("driver", DbConfigFile);
                    return _Driver;
                }
            }
            public static string ConnectionString
            {
                get
                {
                    return "DRIVER={" + Driver + "};" +
                     string.Format("SERVER={0};PORT={1};DATABASE={2};UID={3};PWD={4};OPTION=3",
                                   Server, Port, Dbname, Username, Password);
                }
            }
        }
    }
}
